package cn.yanxiaohui.service.web.mq.exchange;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;

/**
 * 使用direct模式的exchange生产消息
 * @author yanxh
 */
public class DirectProducer {
    private final static String QUEUE_NAME = "ChongDongOrder";

    public static void main(String[] args) throws IOException, Exception {
        /**
         * connection是socket连接的抽象，并且为我们管理协议版本协商（protocol version negotiation），认证（authentication ）等等事情。
         */
        ConnectionFactory factory = new ConnectionFactory();
        // 主机IP
        factory.setHost("127.0.0.1");
        // 端口号
        factory.setPort(5672);
        // 用户名
        factory.setUsername("chongdong");
        // 密码
        factory.setPassword("chongdong");
        // 设置虚拟主机(相当于数据库中的库)
        factory.setVirtualHost("saibeideyu");
        String message = "虫洞空间研发团队测试消息发送带事务...";

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare("我的交换机", "direct"); //direct fanout topic
        channel.queueBind(QUEUE_NAME, "我的交换机", "routingKey123");
        byte[] messageBodyBytes = message.getBytes();
        //需要绑定路由键
        channel.basicPublish("我的交换机", "routingKey123", MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes);
        System.out.println("发送消息【" + message + "】");

        channel.close();
        connection.close();
    }

}
